package com.gz.common;

import com.gz.common.model.Integralrecord;
import com.gz.common.model.User;

public class CentsService {

	private static CentsService centsService = null;

	public static CentsService getCentsService() {
		if (centsService == null) {
			centsService = new CentsService();
		}
		return centsService;
	}

	
	
	/**
	 * 根据分润金额更新购物用户及其关联用户积分
	 * @author yp+sfw
	 * @param id	用户id
	 * @param money	分润金额
	 * @return	int result 更新结果
	 */
	public int fenqian(Integer id, double money) {
		User user = UserService.getService().findUserId(id);
		if(user==null) {
			return -1;
		}
		if (user.getUsergrade() !=0) {
			addJiFen(getAcceptor(1, id), money * 0.2);//直接上级
		}
		if (user.getUsergrade() == 1) {// 会员
			addJiFen(id, money * 0.4);
			addJiFen(getAcceptor(2, id), money * 0.2);
			addJiFen(getAcceptor(3, id), money * 0.05);
			return 1;
		} else if (user.getUsergrade() == 2) {// 分销商
			addJiFen(id, money * 0.5);
			addJiFen(getAcceptor(3, id), money * 0.05);
			return 2;
		} else if (user.getUsergrade() == 3) {// 总经销商
			addJiFen(id, money * 0.7);
			return 3;
		}else {
			return 0;
		}
	}

	/**
	 * 递归直接上级,查找最近的某一级上级(分销或总经销)
	 * @author 尹公子
	 * @param userLevel 要查找的上级的等级
	 * @param userid    用户id
	 * @return
	 */
	public Integer getAcceptor(Integer userLevel, Integer userid) {
		User userAcceptor = ApplicationrecordService.getService().findDJ(userid);// 查询直接上级信息
		if (userAcceptor.getUsergrade() >= userLevel) {// 判断直接上级等级是否满足条件 
			return userAcceptor.getId();//满足条件则返回此直接上级上级id
		} else {
			return getAcceptor(userLevel, userAcceptor.getSuperiorid());//否则将当前用户的直接上级id传入继续递归
		}
	}

	/**
	 * 为指定用户添加积分
	 */
	public boolean addJiFen(Integer id, Double money) {
		// 9:1
		Double jf = money * 1000;
		Integer txjf = (int) Math.round(jf * 0.9);
		Integer xfjf = (int) Math.round(jf * 0.1);
		User user = UserService.getService().findUserId(id);
		user.setConsumption(user.getConsumption() + xfjf);// 消费积分
		user.setAmountS(user.getAmountS() + txjf);// 提现积分
		
		Integralrecord integralrecord = new Integralrecord();
		integralrecord.setGetintegral(txjf+xfjf);//获得的总积分
		integralrecord.setUserid(id);//用户id
		integralrecord.setType(1);//1=分润、2=体现、3=优惠卷消费
		integralrecord.setUseintegral(0);//没有使用积分
		IntegralrecordService.getService().xinZengJiFeng(integralrecord);
		
		return user.update();
	}
	


}
